<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Article;
use App\Models\InPressArticle;
use App\Models\Author;
use App\Models\Issue;
use App\Models\ArticleCat;
use App\Models\Affiliation;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\DB;
use View;


use Illuminate\Support\Facades\Response;

use App\Lib\Export;


class ArticleController extends Controller
{

    public function index($id)
    {
        $article = Article::find($id);
        if (!$article) abort(404);

        $article->view_count = $article->view_count + 1;
        $article->save();

        return view('article.index', ['article' => $article]);
    }


    public function html($id)
    {
        $article = Article::find($id);
        if (!$article) abort(404, 'can not find article, id: ' . $id);
        $htmlDir = config('app.html_dir');

        $path = $article->getHtmlPath($htmlDir);
        // file_get_contents($path)
        // print_r(file_get_contents($path));exit;
        // $content = Response::make(file_get_contents($path), 200)->header('Content-Type', 'text/html');
        // return $content;
        // return response()->view(file_get_contents($path), null, '200')->header('Content-Type', 'html');

        return view('article.html');
    }


    public function press()
    {
        $articles = [];
        return view('article.press', ['articles' => $articles]);
    }

    public function downloadFile(Request $request, $id , $type) 
    {
        $article = Article::find($id);
        $file = explode(' ', $article['title'])[0];
        if ($type == 'pdf') {
            $article->download_count = $article->download_count + 1;
            $article->save();

            if ($article['pdf'] == null ) {
                return redirect()->action('IndexController@index');
            }
            $name = public_path('uploads/'.$article['pdf']);
            if ($name) {
                return response()->download($name, $file);
            }
        }
    }

    public function search(Request $request) 
    {
        $keywords = $request->input('keywords');
        $likeStr = '%' . $keywords . '%';
        $articles = Article::on()
            ->where('title', 'like', $likeStr)
            ->orWhere('keywords', 'like', $likeStr)
            ->orWhere('author_list', 'like', $likeStr)
            ->paginate(10);

        return view('article.search',['articles' => $articles, 'keywords' => $keywords]);
    }

    public function downloadRef($id, $type)
    {
        $article = Article::find($id);
        if (!$article) {
            abort(404, 'can not find article, ID: ' . $id);
        }

        //bibtex|endnote|reference_manager|procite|bibtex|refworks
        
        $typeArr = ['bibtex', 'endnote', 'reference_manager', 'procite', 'refworksbibtex', 'refworks'];

        if (!in_array($type, $typeArr)) {
            abort(404, 'Error type: ' . $type);
        }

        $e = new Export($article);
        $method = 'get' . str_replace('_', '', $type);
        if ($type == 'endnote') {
            return Response::make($e->$method(), '200', array('Content-Disposition'=>sprintf('attachment; filename="%s"', 'EndNote_en.enw')))
                ->header('Content-Type', 'application/x-endnote-refer');
        } else {
            return Response::make($e->$method(), '200', array('Content-Disposition'=>sprintf('attachment; filename="%s"', ucwords($type) . '_en.txt')))
                ->header('Content-Type', 'plain/txt');
        }
    }

    public function downloadMultipleRef(Request $request)
    {
        $ids = $request->get('ids', []);
        $type = $request->get('type');
        $typeArr = ['bibtex', 'endnote', 'reference_manager', 'procite', 'refworksbibtex', 'refworks'];
        if (empty($ids) or !in_array($type, $typeArr)) {
            abort(404, 'Error occurred');
        }


        $articles = Article::find(explode(',', $ids));
        $method = 'get' . str_replace('_', '', $type);
        $string = '';
        foreach ($articles as $article) {
            $e = new Export($article);
            $string .= $e->$method();
        }

        if ($type == 'endnote') {
            return Response::make($string, '200', array('Content-Disposition'=>sprintf('attachment; filename="%s"', 'EndNote_en.enw')))
                ->header('Content-Type', 'application/x-endnote-refer');
        } else {
            return Response::make($string, '200', array('Content-Disposition'=>sprintf('attachment; filename="%s"', ucwords($type) . '_en.txt')))
                ->header('Content-Type', 'plain/txt');
        }
    }

    public function doi($d1, $d2)
    {
        $doi = $d1 . '/' . $d2;

        $article = Article::where('id_doi', $doi)->first();


        if ($article) {
            return redirect()->action('ArticleController@index', ['id' => $article->id]);
        }

        $article = InPressArticle::where('doi_number', $doi)->first();

        if ($article) {
            return redirect()->action('InPressArticleController@index', ['id' => $article->id]);
        }

        abort(404, 'can not found the article with DOI: ' . $doi);
    }
}
